﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public CtrlHuman ctrlHumanPrefab;
    public SyncHuman syncHumanPrefab;

    private Dictionary<string, BaseHuman> clients = new Dictionary<string, BaseHuman>();
    // Start is called before the first frame update
    void Start()
    {
        ChatEventHub.Init();

        NetManager.Manager.AddListener("Connected", OnConnected);   //连接后才去创建人物
        NetManager.Manager.AddListener("Enter", OnEnter);
        NetManager.Manager.AddListener("Move", OnMove);
        NetManager.Manager.AddListener("Leave", OnLeave);
        NetManager.Manager.AddListener("SendChatMsg", OnSendChatMsg);
        NetManager.Manager.ConnectionAsync("127.0.0.1",8888);  
    }

    private void OnConnected(Msg msg)
    {
        Debug.Log("OnConnected:" + msg.ToString());
        CreateCtrlHuman();
        if (!string.IsNullOrEmpty(msg.Value))
        {
            string[] ips = msg.Value.Split('|');
            foreach (var item in ips)
            {
                if (!clients.ContainsKey(item))
                {
                    CreateSyncHuman(item);
                }
            }
        }
    }

    private void OnLeave(Msg msg)
    {
        Debug.Log("OnLeave:" + msg.ToString());
    }

    private void OnMove(Msg msg)
    {
        Debug.Log("OnMove:" + msg.ToString());
        if (!msg.Client.Equals(NetManager.Manager.GetInfo()))
        {
            string[] targetPoss = msg.Value.Split(',');
            Vector3 targetPos = new Vector3(float.Parse(targetPoss[0]), float.Parse(targetPoss[1]), float.Parse(targetPoss[2]));
            //移动，msg.Client表示的客户端移动
            BaseHuman human = clients[msg.Client];
            human.MoveTo(targetPos);
        }
    }

    public void OnEnter(Msg msg)
    {
        Debug.Log("OnEnter:" + msg.ToString());
        //判断当前信息宿主是否自己
        if (!msg.Client.Equals(NetManager.Manager.GetInfo()))
        {
            CreateSyncHuman(msg.Client);
        }
    }

    private void OnSendChatMsg(Msg msg)
    {
        ChatEventHub.I.NotifyChatMsg(msg.Client, msg.Value);
    }

    private void CreateSyncHuman(string clientID)
    {
        SyncHuman syncHuman = Instantiate(syncHumanPrefab);
        syncHuman.ClientID = clientID;
        clients.Add(clientID, syncHuman);
    }

    private void CreateCtrlHuman()
    {
        CtrlHuman ctrlHuman = Instantiate(ctrlHumanPrefab);
        ctrlHuman.ClientID = NetManager.Manager.GetInfo();
        Msg msg = new Msg();
        msg.Command = "Enter";
        msg.Value = "0,0,0";        
        NetManager.Manager.SendAsync(msg);
        clients.Add(NetManager.Manager.GetInfo(),ctrlHuman);
    }
    // Update is called once per frame
    void Update()
    {
        NetManager.Manager.Update();
    }

    private void OnDestroy()
    {
        NetManager.Manager.CloseSocket();
    }
}
